import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule, ReactiveFormsModule, FormGroup, FormBuilder, Validators } from '@angular/forms';
import { ListService, PagedResultDto } from '@abp/ng.core';
import { FleetcarService } from './fleetcar.service';
import { FleetcarDto, CreateUpdateFleetcarDto } from './models';
import { Subscription } from 'rxjs';
import { finalize } from 'rxjs/operators';
import { VehicleService } from '../Vehicle/vehicle.service';
import { CarInventryService } from '../carInventry/carinventry.service';

@Component({
  selector: 'app-fleetcar',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule],
  templateUrl: './fleetcar.component.html',
  styleUrls: ['./fleetcar.component.scss'],
  providers: [ListService]
})
export class FleetcarComponent implements OnInit, OnDestroy {
  fleetcars = { items: [], totalCount: 0 } as PagedResultDto<FleetcarDto>;
  createFleetcarForm: FormGroup;
  isModalOpen = false;
  isEditMode = false;
  selectedFleetcarId: string;
  isSaving = false;
  Math = Math;

  pageSizeOptions = [10, 20, 30, 50];
  currentPageSize = 10;
  maxPageCount = 1;
  visiblePageNumbers: number[] = [];
  inputPageNumber: number = 1;

  private subscription: Subscription = new Subscription();

  fleetcarNumberKeyword = '';
  driverKeyword = '';
  contactKeyword = '';
  isSearchMode = false;
  isLoading = false;

  vehicleNumbers: any[] = [];
  vehicleNumberKeyword = '';

  dispatchDriverKeyword = '';

  drivers: any[] = [];

  dispatchVehicleNumber = '';

  constructor(
    public readonly list: ListService,
    private fleetcarService: FleetcarService,
    private fb: FormBuilder,
    private vehicleService: VehicleService,
    private carInventryService: CarInventryService
  ) {
    this.createFleetcarForm = this.fb.group({
      shipper: ['', Validators.required],
      shipperPhone: ['', Validators.required],
      shipperAddress: ['', Validators.required],
      consignee: ['', Validators.required],
      consigneePhone: ['', Validators.required],
      consigneeAddress: ['', Validators.required],
      goods: ['', Validators.required],
      pieceCount: [1, [Validators.required, Validators.min(1)]],
      declaration: ['自提', Validators.required],
      lengthm: [1, [Validators.required, Validators.min(0)]],
      widthm: [1, [Validators.required, Validators.min(0)]],
      heightm: [1, [Validators.required, Validators.min(0)]],
      weightk: [1, [Validators.required, Validators.min(0)]],
      freightAmount: [0, [Validators.required, Validators.min(0)]],
      returnRequired: ['否', Validators.required],
      status: [true],
      customerNo: [null, Validators.required],
      remarks: [''],
      orderNo: [null],
    });
  }

  ngOnInit() {
    this.list.page = 1;
    this.loadData();
    this.loadVehicleNumbers();
    this.drivers = [
      { name: '张三', phone: '13800138001' },
      { name: '李四', phone: '13800138002' },
      { name: '王五', phone: '13800138003' }
    ];
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

  loadData() {
    if (this.list.page <= 0) {
      this.list.page = 1;
    }
    this.isLoading = true;
    const streamCreator = (query) => {
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      return this.fleetcarService.getList(params);
    };
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(finalize(() => { this.isLoading = false; }))
        .subscribe(
          (response: PagedResultDto<FleetcarDto>) => {
            let items = response.items;
            if (this.isSearchMode) {
              items = items.filter(item => {
                const vehicleNumberMatch = !this.vehicleNumberKeyword.trim() || (item.VehicleNumber && item.VehicleNumber.includes(this.vehicleNumberKeyword.trim()));
                const fleetcarNumberMatch = !this.fleetcarNumberKeyword.trim() || (item.OrderNo && item.OrderNo.toString().includes(this.fleetcarNumberKeyword.trim()));
                const driverMatch = !this.driverKeyword.trim() || (item.Shipper && item.Shipper.includes(this.driverKeyword.trim()));
                const contactMatch = !this.contactKeyword.trim() || (item.Consignee && item.Consignee.includes(this.contactKeyword.trim()));
                return vehicleNumberMatch && fleetcarNumberMatch && driverMatch && contactMatch;
              });
            }
            this.fleetcars = { ...response, items };
            if (response.totalCount > 0) {
              this.maxPageCount = Math.ceil(response.totalCount / this.currentPageSize);
              if (this.list.page > this.maxPageCount) {
                this.list.page = this.maxPageCount;
                if (response.items.length === 0) {
                  this.loadDataWithoutCheck();
                }
              }
            } else {
              this.maxPageCount = 1;
              this.list.page = 1;
            }
            this.updateVisiblePageNumbers();
          },
          error => {
            // 错误处理
          }
        )
    );
  }

  loadDataWithoutCheck() {
    this.isLoading = true;
    const streamCreator = (query) => {
      const params = {
        ...query,
        maxResultCount: this.currentPageSize,
        skipCount: (this.list.page - 1) * this.currentPageSize
      };
      return this.fleetcarService.getList(params);
    };
    this.subscription.add(
      this.list.hookToQuery(streamCreator)
        .pipe(finalize(() => { this.isLoading = false; }))
        .subscribe(
          (response: PagedResultDto<FleetcarDto>) => {
            this.fleetcars = response;
            this.updateVisiblePageNumbers();
          },
          error => {
            // 错误处理
          }
        )
    );
  }

  updateVisiblePageNumbers() {
    const currentPage = this.list.page || 1;
    const pageNumbers = [];
    if (this.maxPageCount <= 5) {
      for (let i = 1; i <= this.maxPageCount; i++) {
        pageNumbers.push(i);
      }
    } else {
      if (currentPage > 3) {
        pageNumbers.push(1, -1);
      }
      let start = Math.max(1, currentPage - 2);
      let end = Math.min(this.maxPageCount, currentPage + 2);
      for (let i = start; i <= end; i++) {
        pageNumbers.push(i);
      }
      if (end < this.maxPageCount) {
        pageNumbers.push(-1, this.maxPageCount);
      }
    }
    this.visiblePageNumbers = pageNumbers;
  }

  onPageSizeChange(pageSize: number) {
    this.currentPageSize = pageSize;
    this.list.page = 1;
    this.loadData();
  }

  goToPage(page: number) {
    if (page < 1 || page > this.maxPageCount) return;
    this.list.page = page;
    this.loadData();
  }

  onPageInputChange(event: Event) {
    const value = (event.target as HTMLInputElement).value;
    const page = Number(value);
    if (!isNaN(page)) {
      this.inputPageNumber = page;
    }
  }

  onPageInputKeyUp(event: KeyboardEvent) {
    if (event.key === 'Enter') {
      this.goToPage(this.inputPageNumber);
    }
  }

  search() {
    this.isSearchMode = true;
    this.list.page = 1;
    this.loadData();
  }

  resetSearch() {
    this.fleetcarNumberKeyword = '';
    this.driverKeyword = '';
    this.contactKeyword = '';
    this.isSearchMode = false;
    this.list.page = 1;
    this.loadData();
  }
  openCreateModal() {
    this.isModalOpen = true;
    this.isEditMode = false;
    const now = new Date();
    const pad = (n: number, len = 2) => n.toString().padStart(len, '0');
    const orderNo =
      now.getFullYear().toString() +
      pad(now.getMonth() + 1) +
      pad(now.getDate()) +
      pad(now.getHours()) +
      pad(now.getMinutes()) +
      pad(now.getSeconds()) +
      pad(now.getMilliseconds(), 3);
    this.createFleetcarForm.reset({
      shipper: '',
      shipperPhone: '',
      shipperAddress: '',
      consignee: '',
      consigneePhone: '',
      consigneeAddress: '',
      goods: '',
      pieceCount: 1,
      declaration: '自提',
      lengthm: 1,
      widthm: 1,
      heightm: 1,
      weightk: 1,
      freightAmount: 0,
      returnRequired: '否',
      status: true,
      customerNo: null,
      remarks: '',
      orderNo: orderNo,
    });
  }

  openEditModal(fleetcarId: string) {
    this.isModalOpen = true;
    this.isEditMode = true;
    this.selectedFleetcarId = fleetcarId;
    this.fleetcarService.get(fleetcarId).subscribe(
      (fleetcarData) => {
        this.createFleetcarForm.patchValue(fleetcarData);
        if (fleetcarData.OrderNo) {
          this.createFleetcarForm.addControl('OrderNo', this.fb.control(fleetcarData.OrderNo));
        }
      },
      (error) => {
        this.closeModal();
      }
    );
  }

  closeModal() {
    this.isModalOpen = false;
    this.createFleetcarForm.reset();
    this.createFleetcarForm.patchValue({
      fleetNumber: '',
      fleetName: '',
      phone: '',
      address: '',
      mainContact: '',
      mobile: '',
      remarks: ''
    }, {emitEvent: false});
  }

  save() {
    if (this.createFleetcarForm.invalid) {
      Object.keys(this.createFleetcarForm.controls).forEach(key => {
        const control = this.createFleetcarForm.get(key);
        control.markAsDirty();
        control.markAsTouched();
      });
      return;
    }
    const fleetcarData = this.createFleetcarForm.value as CreateUpdateFleetcarDto;
    this.isSaving = true;
    if (this.isEditMode) {
      this.fleetcarService.update(this.selectedFleetcarId, fleetcarData).subscribe(
        () => {
          this.isModalOpen = false;
          this.createFleetcarForm.reset();
          this.loadData();
          this.isSaving = false;
        },
        (error) => {
          this.isSaving = false;
        }
      );
    } else {
      this.fleetcarService.create(fleetcarData).subscribe(
        () => {
          this.isModalOpen = false;
          this.createFleetcarForm.reset();
          this.loadData();
          this.isSaving = false;
        },
        (error) => {
          this.isSaving = false;
        }
      );
    }
  }

  deleteFleetcar(fleetcarId: string) {
    if (!window.confirm('确定要删除该车辆吗？')) {
      return;
    }
    this.fleetcarService.delete(fleetcarId).subscribe(
      () => {
        if (this.fleetcars.items.length === 1 && this.list.page > 1) {
          this.list.page--;
        }
        this.loadData();
      },
      (error) => {
      }
    );
  }

  loadVehicleNumbers() {
    this.vehicleService.getVehicleNumberLookup().subscribe(res => {
      this.vehicleNumbers = res.items || res;
    });
  }

  onVehicleNumberChange(fleetcar, newVehicleNumber) {
    fleetcar.vehicleNumber = newVehicleNumber;
    // 如需保存到后端，可在此调用保存接口
  }

  dispatch(fleetcar) {
    alert(`派车：${fleetcar.orderNo || fleetcar.OrderNo}`);
  }

  setAllDrivers(driverName: string) {
    for (let fleetcar of this.fleetcars.items) {
      if ('driverName' in fleetcar) {
        fleetcar.driverName = driverName;
      } else if ('DriverName' in fleetcar) {
        fleetcar.DriverName = driverName;
      }
    }
  }

  get filteredFleetcars() {
    if (!this.vehicleNumberKeyword) {
      return this.fleetcars.items;
    }
    return this.fleetcars.items.filter(item =>
      item.VehicleNumber === this.vehicleNumberKeyword
    );
  }

  batchDispatch() {
    if (!this.dispatchVehicleNumber) {
      alert('请选择车辆号');
      return;
    }
    const selected = (this.fleetcars.items as any[]).filter(item => item.selected);
    if (selected.length === 0) {
      alert('请先勾选要派车的数据');
      return;
    }
    let count = 0;
    for (const fleetcar of selected) {
      // 组装carInventry数据，带上选中的车辆号
      const data = {
        ...fleetcar,
        vehicleNumber: this.dispatchVehicleNumber // 强制覆盖为选中的车辆号
      };
      this.carInventryService.create(data).subscribe({
        next: () => {
          this.fleetcarService.delete(fleetcar.id || fleetcar.Id || fleetcar.fleetcarId).subscribe(() => {
            count++;
            if (count === selected.length) {
              this.loadData(); // 全部完成后刷新
            }
          });
        },
        error: err => {
          alert('派车失败: ' + (err?.message || '未知错误'));
        }
      });
    }
  }
}